var alarms = [];
var currentAlarms = [];
var table;
var undefinedReplace = '空';
var start = $('#startTime').val();
var end = $('#endTime').val();
var stationId = $('#stationId').val();
var columns = [ locale.XuHao, locale.ShouCiGaoJing, locale.DianYa, locale.XianLu, locale.BaoHu, locale.ZongJi,
        		locale.mingXi ];
var initColumns = columns;
var linesLength = 0;
var voltagesLength = 2;
function init() {
	$('#start').val($('#startTime').val());
	$('#end').val($('#endTime').val());
	$('#stationId').val($('#stationId').val());
	$('#start').datetimepicker({
		format : 'yyyy-mm-dd',
		minView : 2,
		autoclose : true,
		endDate : new Date(),
		todayHighlight : true
	});
	$('#end').datetimepicker({
		format : 'yyyy-mm-dd',
		minView : 2,
		autoclose : true,
		endDate : new Date(),
		pickerPosition : 'bottom-left',
		todayHighlight : true
	});
	loadColumnsFilter(initColumns);
	$.ajaxSettings.async = false;
	loadData();
	$.ajaxSettings.async = true;
	$('#alarmTable tbody')
			.on(
					'click',
					'td.details-control',
					function() {
						var tr = $(this).closest('tr');
						var row = table.getTable().row(tr);
						if (row.child.isShown()) {
							// This row is already open - close it
							row.child.hide();
							tr.removeClass('shown');
						} else {
							// Open this row
							var rowIndex = row.data()[0] - 1;
							var detailTableId = 'rowDetail' + rowIndex
									+ 'Table';
							row.child(format(detailTableId)).show();
							loadDetailTable(detailTableId, rowIndex);
							tr.addClass('shown');
						}
						function format(id) {
							return '<table id="'
									+ id
									+ '"  class="table table-bordered table-blue"></table>';

						}
					});
}
function loadData() {
	var loading = layer.load(2,{shade:[0.1,'black']});
	$.getJSON("/rest/protectAlarm/getFrequentDoubleChannelAlarm/" + start + "/"
			+ end, function(result) {
		alarms = result;
		if (stationId == "" || stationId == null || typeof (stationId) == "undefined") {
			loadFilter(stationId);
		} else {
			$('#selectButton').hide();
		}
		currentAlarms = [];
		if (stationId) {
			for ( var i in alarms) {
				if (alarms[i].stationId == stationId) {
					currentAlarms.push(alarms[i]);
				}
			}
			loadContent(currentAlarms);
		} else {
			currentAlarms = alarms;
			loadContent(alarms);
		}
		stationId = undefined;
		layer.close(loading);
	});
}
function query() {
	var s = $('#start').val();
	var e = $('#end').val();
	if (s == start && e == end) {
		doFilter();
	} else {
		start = s;
		end = e;
		loadData();
	}
}
function loadFilter() {
	var lines = [];
	var lineMap = {};
	for ( var i in alarms) {
		var a = alarms[i];
		var line = a.lineName ? a.lineName : undefinedReplace;
		if (lines.indexOf(line) == -1) {
			lines.push(line);
		}
		// 加title
		var l = lineMap[line];
		if (!l) {
			l = {
				count : 0
			};
			lineMap[line] = l;
		}
		l.count++;
	}
	// 先按照count排，count相同按照总时长
	lines.sort(sortLines);
	linesLength = lines.length;
	$('#lines').html(getCheckBox(lines, 'lines', 'doFilter();', null, lines));
	selectAllVoltages();
	function selectAllVoltages() {
		var ss = document.getElementsByName("voltages");
		var ssAll = document.getElementById("voltagesAll");
		ssAll.checked = true;
		for ( var i in ss) {
			ss[i].checked = true;
		}
	}
	function sortLines(line1, line2) {
		var t1 = line1 == undefinedReplace ? 0 : 1;
		var t2 = line2 == undefinedReplace ? 0 : 1;
		if (t2 + t1 < 2) {
			return t2 - t1;
		}
		var m1 = lineMap[line1];
		var m2 = lineMap[line2];
		return m2.count - m1.count;
	}
}
function loadColumnsFilter(selectColumns) {
	if (!selectColumns) {
		selectColumns = columns;
	}
	$('#columns').html(
			getCheckBox(columns, 'columns', 'doColumnFilter();', null,
					selectColumns));
}
function doFilter() {
	var lines = getCheckBoxValue('lines');
	var voltages = getCheckBoxValue('voltages');
	changeSelectButtonStatus(lines, voltages);
	currentAlarms = [];
	for ( var i in alarms) {
		var a = alarms[i];
		var line = a.lineName ? a.lineName : undefinedReplace;
		var voltage = a.voltage ? a.voltage : undefinedReplace;
		if (lines.indexOf(line) > -1 && voltages.indexOf(voltage) > -1) {
			currentAlarms.push(a);
		}
	}
	loadContent(currentAlarms);
}
function changeSelectButtonStatus(lines, voltages) {
	if (lines.length == linesLength && voltages.length == voltagesLength) {
		$('#selectButton').removeClass('hasSelected');
	} else {
		$('#selectButton').addClass('hasSelected');
	}
}
function changeColumnsSelectButtonStatus(length) {
	if (columns.length == length) {
		$('#columnsSelectButton').removeClass('hasSelected');
	} else {
		$('#columnsSelectButton').addClass('hasSelected');
	}
}
function getCheckBoxValue(name) {
	var obj = document.getElementsByName(name);
	var s = [];
	for (var i = 0; i < obj.length; i++) {
		if (obj[i].checked) {
			s.push(obj[i].value);
		}
	}
	return s;
}
function getCheckBox(data, name, func, map, selects) {
	var c = '';
	for ( var i in data) {
		if (map) {
			var item = map[data[i]];
			var count = item.count;
			var checked = '';
			if (selects.indexOf(data[i]) > -1) {
				checked = ' checked = "checked" ';
			}
			c += '<label title="告警' + count + '次"><input name="' + name
					+ '" type="checkbox" onchange="' + func + '" ' + checked
					+ ' value="' + data[i] + '" />' + data[i] + '</label>';
		} else {
			var checked = '';
			if (selects.indexOf(data[i]) > -1) {
				checked = ' checked = "checked" ';
			}
			c += '<label><input name="' + name + '" type="checkbox" onchange="'
					+ func + '" ' + checked + ' value="' + data[i] + '" />'
					+ data[i] + '</label>';
		}

	}
	return c;
}
function loadContent(alarms) {
	loadTable(alarms);
	refreshAllSelectAllButtonStatus();
}
function loadTable(alarms) {
	if (table) {
		table.getTable().destroy();
	}
	var opt = MyTable.getDefaultOptions();
	opt.paging = false;
	opt.autoWidth = false;
	var defs = [ {
		targets : 0,
		width : '3%'
	}, {
		targets : 1,
		width : '15%'
	}, {
		targets : 2,
		width : '5%'
	}, {
		targets : 3,
		width : '7%'
	}, {
		targets : 4,
		width : '20%'
	}, {
		targets : 5,
		width : '10%'
	}, {
		targets : 6,
		width : '5%',
		className : "details-control"
	} ];
	opt.scrollY = scrollYHeight;
	opt.scrollX = false;
	var datas = [];
	var totalMils=0;//总时间毫秒数
	var totalTimes=0;//总次数
	for ( var i in alarms) {
		var f = alarms[i];
		var as = f.alarms;
		totalMils+=f.continueMs;
		var startTime = time(as[0].eventStart) + '.' + str(as[0].mStartMs);
		var t = (f.continueMs / 60000).toFixed(2);
		var count = '<span style="color:red;margin:3px;">' + t + '</span>分钟';
		datas.push([ Number(i) + 1, startTime, str(f.voltage), str(f.lineName),
				str(f.protectName), count, '' ]);
		for(var j in as){
			if(as[j].channelAlarms && as[j].channelAlarms.length > 0){
				totalTimes++;
				break;
			}
		}
	}
	// 筛选列
	var eles = document.getElementsByName('columns');
	var targets = [];
	for (var i = 0; i < eles.length; i++) {
		if (!eles[i].checked) {
			targets.push(i);
		}
	}
	defs.push({
		visible : false,
		targets : targets
	});
	opt.columnDefs = defs;
	table = new MyTable("alarmTable", columns, opt);
	table.setDataSet(datas).show();
	$("#totalNum").html(alarms.length);
	$("#totalMinutes").html(totalMils>0?(totalMils / 60000).toFixed(2):totalMils);
	$("#totalTimes").html(totalTimes);
}
function minusTime(t1, t2) {
	var d1 = new Date(t1.time ? t1.time : t1);
	var d2 = new Date(t2.time ? t2.time : t2);
	return ((d1.getTime() - d2.getTime()) / 60000).toFixed(2);
}
function loadDetailTable(tableId, rowIndex) {
	var as = currentAlarms[rowIndex].alarms;
	var columns = [ locale.XuHao, locale.GaoJingShiJian, locale.BianDianZhan, locale.BaoHu, locale.GaoJingNeiRong, locale.ZhongDuanShiChang,locale.YiChangDingWei];
	var dataset = [];
	var opt = MyTable.getDefaultOptions();
	opt.paging = false;
	opt.autoWidth = false;
	var defs = [ {
		targets : 0,
		width : '5%'
	}, {
		targets : 1,
		width : '10%'
	}, {
		targets : 2,
		width : '7%'
	}, {
		targets : 3,
		width : '22%'
	}, {
		targets : 4,
		width : '15%'
	}, {
		targets : 5,
		width : '13%'
	}, {
		targets : 6,
		width : '20%'
	} ];
	opt.scrollY = "300px";
	opt.scrollX = false;
	opt.scrollCollapse = true;
	for (var i = 0; i < as.length; i++) {
		var f = as[i];
		var channels = "<span style='color:gray;'>无通道告警信息</span>";
		if (f.channelAlarms && f.channelAlarms.length > 0) {
			channels = "<ul>";
			for ( var j in f.channelAlarms) {
				var a = f.channelAlarms[j];
				channels += "<li>" + a.alarmChannel + "</br>" + a.alarmObject
						+ "</br><span style='color:red;'>" + a.name
						+ "</span></li>";
			}
			channels += "</ul>";
		}
		var durationTime = f.durationTime;
		var title = '';
		if (durationTime) {
			title = 'title="' + (durationTime / 60000).toFixed(2) + '分钟"';
			durationTime = durationTime + 'ms';
		} else {
			durationTime = '未复归';
		}
		durationTime = '<span ' + title + ' style="color:red;">' + durationTime
				+ '</span>';
		dataset.push([ Number(i) + 1, time(f.eventStart) + '.' + f.mStartMs,
				str(f.stationName), str(f.protectName), str(f.alarmMsg),
				durationTime, channels ]);
	}
	opt.columnDefs = defs;
	var table = new MyTable(tableId, columns, opt);
	table.setDataSet(dataset).show();
}
function selectAll(isChecked, name) {
	var eles = document.getElementsByName(name);
	for (var i = 0; i < eles.length; i++) {
		eles[i].checked = isChecked;
	}
	doFilter();
}
function selectAllColumns(isChecked, name) {
	var eles = document.getElementsByName(name);
	for (var i = 0; i < eles.length; i++) {
		eles[i].checked = isChecked;
	}
	doColumnFilter();
}
function doColumnFilter() {
	var eles = document.getElementsByName("columns");
	var length = 0;
	for (var i = 0; i < eles.length; i++) {
		var show = eles[i].checked;
		var col = table.getTable().column(i);
		col.visible(show);
		if (show) {
			length++;
		}
	}
	changeColumnsSelectButtonStatus(length);
	redrawTable();
}
function redrawTable() {
	if (table) {
		table.getTable().draw();
	}
	// $.fn.dataTable.tables( {visible: true, api: true} ).columns.adjust();
}
function str(v) {
	return v ? v : '';
}
function time(v) {
	return DateUtil.locale(v)+':'+DateUtil.pattern(v,'ss');
}
function refreshAllSelectAllButtonStatus() {
	var ids = [ 'columns', 'lines', 'voltages' ];
	for ( var i in ids) {
		refreshSelectAllButtonStatus(ids[i]);
	}
}
function refreshSelectAllButtonStatus(id) {
	var eles = document.getElementsByName(id);
	var all = document.getElementById(id + 'All');
	var checked = true;
	for (var i = 0; i < eles.length; i++) {
		var show = eles[i].checked;
		if (!show) {
			checked = false;
			break;
		}
	}
	all.checked = checked;
}

function resizeHtml() {
	if (table) {
		table.getTable().draw();
	}
}